package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.constant.StatusConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.LoginUser;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.*;
import com.zzyl.mapper.LoginMapper;
import com.zzyl.service.LoginService;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    LoginMapper loginMapper;

    private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    // 登录功能
    @Override
    public UserLoginVo login(LoginDto loginDto) {
        String username = loginDto.getUsername();
        String password = loginDto.getPassword();

        // 账号是否为空, 若为空出错误提示
        if (StringUtils.isEmpty(username)) {
            // 账号不能为空
            throw new AccountIsNullException(BasicEnum.LOGIN_ACCOUNT_IS_NULL);
        }

        // 密码是否为空，若为空出错误提示
        if (StringUtils.isEmpty(password)) {
            // 密码不能为空
            throw new PasswordIsNullException(BasicEnum.LOGIN_PASSWORD_IS_NULL);
        }

        // 查询sys_user表中的username
        LoginUser loginUser = loginMapper.getByUsername(username);

        if (loginUser == null) {
            // 用户登录失败
            throw new LoginFailedException(BasicEnum.LOGIN_FAIL);
        }
        if (loginUser.getDataState().equals(StatusConstant.DISABLE)) {
            // 账号已禁用,请联系管理员
            throw new AccountDisableException(BasicEnum.LOGIN_ACCOUNT_DISABLE);
        }

        // 判断password 和 user中的password是否一致
        if (!bCryptPasswordEncoder.matches(password,loginUser.getPassword())) {
            // 将用户输入的明文密码 password 与数据库中存储的哈希值 user.getPassword()
            // 进行比对，返回一个布尔值表示密码是否匹配
            // 用户名或密码错误
            throw new PasswordErrorException(BasicEnum.LOGIN_ACCOUNTORPASSWORD_ERROR);
        }

        // 账号与密码匹配，未配置菜单权限

        // 账号与密码匹配
        return BeanUtil.toBean(loginUser, UserLoginVo.class);
    }
}
